#include "cAudio.h"

cAudio::cAudio()
{
	//Create the system device
	m_result = FMOD::System_Create(&m_pSystem);
	FMODErrorCheck(m_result);

	//Check the version of FMOD
	m_result = m_pSystem->getVersion(&m_version);
	FMODErrorCheck(m_result);

	if(m_version < FMOD_VERSION)
	{
		//MessageBox(0, "Error! You are using an old verson of FMOD!", 0, 0);
	}

	//Get the number of sound cards result
	m_result = m_pSystem->getNumDrivers(&m_numDrivers);
	FMODErrorCheck(m_result);

	//Check to see if there are any cards attached
	if(m_numDrivers == 0)
	{
		m_result = m_pSystem->setOutput(FMOD_OUTPUTTYPE_NOSOUND);
		FMODErrorCheck(m_result);
	}

	else
	{
		m_result = m_pSystem->getDriverCaps(0, &m_caps, 0, &m_speakerMode);
		FMODErrorCheck(m_result);

		m_result = m_pSystem->setSpeakerMode(m_speakerMode);
		FMODErrorCheck(m_result);

		if(m_caps & FMOD_CAPS_HARDWARE_EMULATED)
		{
			m_result = m_pSystem->setDSPBufferSize(1024, 10);
			FMODErrorCheck(m_result);
		}

		m_result = m_pSystem->getDriverInfo(0, m_name, 256, 0);
		FMODErrorCheck(m_result);

		if(strstr(m_name, "SigmaTel"))
		{
			m_result = m_pSystem->setSoftwareFormat(48000, FMOD_SOUND_FORMAT_PCMFLOAT, 0, 0, 
				FMOD_DSP_RESAMPLER_LINEAR);
			FMODErrorCheck(m_result);
		}

	}

	//Initialize the FMOD System
	m_result = m_pSystem->init(100, FMOD_INIT_NORMAL, 0);
	if(m_result == FMOD_ERR_OUTPUT_CREATEBUFFER)
	{
		m_result = m_pSystem->setSpeakerMode(FMOD_SPEAKERMODE_STEREO);
		FMODErrorCheck(m_result);

		m_result = m_pSystem->init(100, FMOD_INIT_NORMAL, 0);
	}
	FMODErrorCheck(m_result);
}

cAudio::~cAudio()
{
	if(m_pSystem != NULL)
	{
		m_pSystem->release();
		m_pSystem = NULL;
	}
}

void cAudio::FMODErrorCheck(FMOD_RESULT result)
{
	if(result != FMOD_OK)
	{
		MessageBox(0, "Error Object Cannot be initialized!", 0, 0);
		exit(-1);
	}
}

void cAudio::play(FMOD::Sound *sound)
{
	//Check to see if the sound is playing
	
	//Play the sound if the condition is false

	//switch the is playing to true

	//Else stop the playback

	//Then play the sound
	m_pSystem->playSound(FMOD_CHANNEL_FREE, sound, false, &m_pChannel);
}

void cAudio::pause(FMOD::Sound *sound)
{
	//Check to see if the sound is playing
	
	//Pause the sound and continue with the program execution 

	//Else Do nothing
}

bool cAudio::isLooping()
{ 
	//Check the setting on the looping status

	//Set it equal to the 
	return m_bIsLooping;
}

void cAudio::changeLoop(bool bIsLooping)
{
}

cSound* cAudio::makeSound(char *fileName)
{
	if(fileName != NULL)
	{
		//Provides a new sound given the
		return new cSound(fileName);
	}
	
	return NULL;
}

cMusic* cAudio::makeMusic(char *fileName)
{
	if(fileName != NULL)
	{
		return new cMusic(fileName);
	}

	return NULL;
}